#include "image_loader.h"
#include "crc16.hpp"
#include "string.h"
#include "apm32a10x.h"
#include "apm32a10x_rcm.h"
#include "stdio.h"

static const char IMAGE_MAGIC_NUMBER[4] = {'I','M','G',0};

IL_RET_t ImageLoader_checkImage(ImageHeader_t *image){
    /* Check image format. */
    if ( memcmp(IMAGE_MAGIC_NUMBER,image->magic_number,4) != 0 ){
        return IL_UNKNOWN_FORMAT;
    }
    /* Validify CRC-16. */
    if( image->length > 0x00040000) return IL_ERROR;
    uint16_t crc16_cal = crc16((unsigned char*)((unsigned int)image + IMAGE_CONTEXT_OFFSET),image->length - IMAGE_CONTEXT_OFFSET);
    if ( crc16_cal != image->crc16 ){
        return IL_CRC_CHECK_FAILED;
    }
    return IL_OK;
}
